<?php
/**
 * 网页授权
 */

class Oauth extends Control{
    //登录测试号找到自己的APPID和APPsecret
	private $appId = '你的appid';   
	private $appSecret = '你的appsecret';

	public function _GET(){
        //普通获得的access_token,通过基础支持中的“获取access_token”接口来获取到的普通access_token调用。
		$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appId.'&secret='.$this->appSecret;
		$access_token = $this->red('cache')->get('access_token');//暂存缓存
		if(!$access_token){
			$token = $this->http_request($url);
			$access_token = $token['access_token'];
			$this->red('cache')->setex('access_token',7200,$this->access_token);
		}
	}
	//获取code
	public function oauthUrl($redirect_url, $scope, $state=NULL){
		$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->appId."&redirect_uri=".$redirect_url."&response_type=code&scope=".$scope."&state=".$state."#wechat_redirect";
        return $url;
	}
	//生成oauth2的access_token,获取网页授权的access_token，可以用来调用获取用户的基本信息
	public function oauth2_access_token($code){
		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appId."&secret=".$this->appSecret."&code=".$code."&grant_type=authorization_code";
        $res = $this->http_request($url);
        return json_decode($res, true);
	}
	//获取用户基本信息（OAuth2 授权的 Access Token 获取 未关注用户，Access Token为临时获取）
    public function oauth2_get_user_info($access_token, $openid){
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
        $res = $this->http_request($url);
        return json_decode($res, true);
    }
    //获取用户基本信息
    public function get_user_info($openid){
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$this->access_token."&openid=".$openid."&lang=zh_CN";
        $res = $this->http_request($url);
        return json_decode($res, true);
    }
    //curl函数模拟浏览器
	protected function http_request($url, $data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}
?>